package com.mright.shop.manager.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mright.shop.manager.common.constant.RespBean;
import com.mright.shop.manager.framework.filters.CustomUsernamePasswordAuthenticationFilter;
import com.mright.shop.manager.framework.filters.VerifyCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : zhaochuanzhen
 * @description :
 * @date : 2020/7/29 10:12
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private VerifyCodeFilter verifyCodeFilter;

    /**
     * 用户的配置
     *
     * @param auth 权限
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("zhaochuanzhen").roles("admin", "user").password(passwordEncoder.encode("123456"))
                .and()
                .withUser("chenduxiu").roles("user").password(passwordEncoder.encode("123456"));
    }

    /**
     * 登录配置
     *
     * @param http http安全配置
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);

        http.authorizeRequests()
                .antMatchers("/user/login").hasRole("admin")
                .antMatchers("/img/**", "/vercode").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/doLogin")
                .loginProcessingUrl("/login")
                .successHandler((request, response, authentication) -> {
                    RespBean ok = RespBean.ok("登录成功!", authentication.getPrincipal());
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(new ObjectMapper().writeValueAsString(ok));
                    writer.flush();
                    writer.close();
                })
                .failureHandler((request, response, exception) -> {
                    RespBean error = RespBean.error("登录失败!");
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(new ObjectMapper().writeValueAsString(error));
                    writer.flush();
                    writer.close();
                })
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((request, response, authentication) -> {
                    RespBean ok = RespBean.ok("注销成功!");
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(new ObjectMapper().writeValueAsString(ok));
                    writer.flush();
                    writer.close();
                })
                .permitAll()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        RespBean error = RespBean.error("权限不足!");
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        writer.write(new ObjectMapper().writeValueAsString(error));
                        writer.flush();
                        writer.close();
                    }
                });

        http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    CustomUsernamePasswordAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomUsernamePasswordAuthenticationFilter filter = new CustomUsernamePasswordAuthenticationFilter();
        filter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            RespBean ok = RespBean.ok("登录成功!", authentication.getPrincipal());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(ok));
            writer.flush();
            writer.close();
        });
        filter.setAuthenticationFailureHandler((request, response, exception) -> {
            RespBean error = RespBean.error("登录失败!");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(error));
            writer.flush();
            writer.close();
        });

        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

    @Bean
    RoleHierarchy roleHierarchy(){
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy("ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user");
        return roleHierarchy;
    }
}
